package com.it.test;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.channels.MulticastChannel;
import java.util.UUID;

@Controller
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(String userName, MultipartFile[] fileName) throws IOException {
        //使用MultipartFile接收文件对象，方法形参名称要入form表单控件项名称一致！
        System.out.println(userName);
        for (MultipartFile multipartFile : fileName) {
            //获取form表单中文件控件的name==》fileName
            String inputname = multipartFile.getName();
            System.out.println(inputname);
            //获取文件的原始的名称
            String originalFilename = multipartFile.getOriginalFilename();
            System.out.println(originalFilename);
            //获取文件的后缀
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
            System.out.println(suffixName);
            //避免上传的文件名字相同而覆盖，使用UUID随机生成id+后缀名
            UUID uuid = UUID.randomUUID();

            //生成新文件名
            String newName=uuid+suffixName;

            //把文件上传保存到指定路径
            File file = new File("C:\\Users\\曦月丶\\Desktop\\imgs",newName);

            //文件转存到本地
            multipartFile.transferTo(file);

        }

        return "true";

    }
}
